﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Instance;
using XuanXiang.Service.Interface;

namespace XuanXiang.Api.Admin.Controllers
{

    [ApiGroup("Admin(管理员模块)")]
    public class LoginController : BaseController
    {
       
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration, I_Login_Service login_Service) : base(login_Service)
        {
            
            _configuration = configuration;
        }

        /// <summary>
        /// 管理员登录
        /// {account/password}
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
     
        public async Task<IActionResult> Logins(Login_dto dto)
        {
            
            dto.code = Config.GUID2();
            var data = await _login_Service.Logins(dto);
            if (data.code == Api_Code.ok)
            {
                var claims = new[]
                    {
                    new Claim(ClaimTypes.Name,  dto.code),
                    new Claim(ClaimTypes.Actor,  dto.account!),
                    new Claim(ClaimTypes.Role,"admin")//角色设定
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 12), //token 过期时间
                    signingCredentials: creds);

                data.data = new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                };

            }

            return Ok(data);
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles="admin")]
        public IActionResult Check_Login()
        {
          
            var user =this.Get_User();
            if (user == null) { 
            return Unauthorized();//401
            }
            return Ok(new Api_Result_Dto() { 
            code=0,
            message="ok",
                data = new{ 
                name=user.name,
                account=user.account
                }
            });
        }



        /// <summary>
        /// 初始化用户密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Init_User()
        {
            var result = await _login_Service.Init_User();
            return Ok(result);
        }

    }
}
